package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

import tokenizer.FixedSeparatorMessageTokenizer;
import tokenizer.StringMessageTokenizer;


public class ServerConnector {
	String host;
	int port;
	final int NUM_OF_BYTES = 1024;
	SocketChannel sChannel;
	ByteBuffer inbuf;
	StringMessageTokenizer tokenizer;
	BufferedReader userIn;
	ByteBuffer outbuf;
	boolean isConnected;
	
	public ServerConnector(String host, int port) throws UnsupportedEncodingException {
		this.host = host;
		this.port = port;
		sChannel = null; // the connection socket
		// used for reading
		inbuf = ByteBuffer.allocate(NUM_OF_BYTES); 
		tokenizer = new FixedSeparatorMessageTokenizer("\n",Charset.forName("UTF-8"));
		userIn = new BufferedReader(new InputStreamReader(System.in,"UTF-8"));
		outbuf = null;
		isConnected = false;
	}
	
	public void connect() throws IOException{
		sChannel=SocketChannel.open();
		try {
			sChannel.connect(new InetSocketAddress(host, port));

			sChannel.configureBlocking(true); 
			System.out.println("Connected to - "+host);
			isConnected = true;
		} catch(IOException e){
			System.out.println("Failed to connected to - "+host);
			sChannel.close();
                        throw e;
		}
		System.out.println("Connected to server!");
		
	}
	
	public String send(String msg) throws IOException{
		if(!isConnected)
			return null;
		
		msg += "\n";
		outbuf = ByteBuffer.wrap(msg.getBytes("UTF-8"));
		while (outbuf.remaining() > 0) {
			sChannel.write(outbuf);
		}
		// read a line from the server and print it
		while (!tokenizer.hasMessage()) {
			inbuf.clear();
			sChannel.read(inbuf);
			inbuf.flip();
			tokenizer.addBytes(inbuf);
		}

		return tokenizer.nextMessage();
	}
	
	public void disconnect() throws IOException{
		// Close all I/O
		sChannel.close();
		userIn.close();
		isConnected = false;
	}

}
